/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package ie.nell.chart;

import java.util.ArrayList;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.graphics.Color;
import android.graphics.Paint.Align;
import ie.nell.ApplicationSettings;
import ie.nell.EventDBOpenHelper;

/**
 * Average temperature demo chart.
 */
public class ClicksChart extends AbstractDemoChart {

    private SQLiteDatabase db;
    private Cursor cursor;
    private String interval = "hour";
    private int noi = 24; // number of intervals to analyse

    public ClicksChart(int noi, String interval) {
        this.interval = interval;
        this.noi = noi;
    }

    /**
     * Shows chart of clicks in last 24 hours
     *
     * @param context the context
     * @return the built intent
     */
    public Intent execute(Context context) {
        String[] titles = new String[]{"clicks", "pages"};
        List<double[]> x = new ArrayList<double[]>();
        List<double[]> values = new ArrayList<double[]>();
        double[] page_hours = new double[noi];
        double[] page_counts = new double[noi];
        double[] click_hours = new double[noi];
        double[] click_counts = new double[noi];
        double max = 0;
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String[] clickSubQueries = new String[noi];
        String[] pageSubQueries = new String[noi];
        db = ApplicationSettings.db;

        for (int i = noi; i > 0; i--) {
            clickSubQueries[noi - i] = "SELECT '" + i + "' AS interval, count() FROM "
                    + EventDBOpenHelper.EVENT_TABLE_NAME
                    + " WHERE time<datetime('now', '-" + (i - 1) + " " + interval + "') AND "
                    + " time>datetime('now', '-" + i + " " + interval + "')";
        }

        String sql = qb.buildUnionQuery(clickSubQueries, null, null);
        Cursor mCursor = db.rawQuery(sql, null);
        double current;
        if (mCursor != null) {
            mCursor.moveToFirst();
            for (int i = 0; i < noi; i++) {
                click_hours[i] = mCursor.getDouble(0);
                current = mCursor.getDouble(1);
                System.out.println("interval " + i + ": " + current);
                click_counts[i] = current;
                max = Math.max(max, current);
                mCursor.moveToNext();
            }
        }
        mCursor.close();
        x.add(click_hours);
        values.add(click_counts);


        for (int i = noi; i > 0; i--) {
            pageSubQueries[noi - i] = "SELECT '" + i + "' AS interval, count() FROM "
                    + EventDBOpenHelper.URL_TABLE_NAME
                    + " WHERE time<datetime('now', '-" + (i - 1) + " " + interval + "') AND "
                    + " time>datetime('now', '-" + i + " " + interval + "')";
        }

        sql = qb.buildUnionQuery(pageSubQueries, null, null);
        mCursor = db.rawQuery(sql, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
            for (int i = 0; i < noi; i++) {
                page_hours[i] = mCursor.getDouble(0);
                current = mCursor.getDouble(1);
                System.out.println("interval " + i + ": " + current);
                page_counts[i] = current;
                max = Math.max(max, current);
                mCursor.moveToNext();
            }
        }
        max = Math.ceil(max / 9.9) * 10.0;
        mCursor.close();
        x.add(page_hours);
        values.add(page_counts);

        int[] colors = new int[]{Color.GREEN, Color.RED};
        PointStyle[] styles = new PointStyle[]{PointStyle.DIAMOND, PointStyle.X};
        XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
        int length = renderer.getSeriesRendererCount();
        for (int i = 0; i < length; i++) {
            ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)).setFillPoints(true);
        }
        setChartSettings(renderer, "Clicks & Pages", "last " + noi + " " + interval, "number of clicks/pages", 0.5, 24.5, 0, max,
                Color.LTGRAY, Color.LTGRAY);
        renderer.setXLabels(6);
        renderer.setYLabels(10);
        renderer.setShowGrid(true);
        renderer.setXLabelsAlign(Align.RIGHT);
        renderer.setYLabelsAlign(Align.RIGHT);
        renderer.setZoomButtonsVisible(true);
        renderer.setPanLimits(new double[]{0, 20, 0, 40});
        renderer.setZoomLimits(new double[]{0, 20, 0, 40});
        renderer.setXAxisMax(noi + 0.5);
        renderer.setXAxisMin(0.5);
        Intent intent = ChartFactory.getLineChartIntent(context, buildDataset(titles, x, values),
                renderer, "UX Browser Charts");
        return intent;
    }
}
